from flask_restful import Resource, reqparse
from flask import request
from models import db, ScheduledTask, User
from utils import api_response
import logging

logger = logging.getLogger(__name__)

class ScheduledTaskList(Resource):
    def get(self):
        """获取定时任务列表"""
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', type=int, location='args')
        parser.add_argument('is_active', type=bool, location='args')
        args = parser.parse_args()
        
        query = ScheduledTask.query
        
        if args['user_id'] is not None:
            query = query.filter_by(user_id=args['user_id'])
            
        if args['is_active'] is not None:
            query = query.filter_by(is_active=args['is_active'])
        
        tasks = query.order_by(ScheduledTask.created_at.desc()).all()
        
        return api_response({
            'tasks': [task.to_dict() for task in tasks]
        })
    
    def post(self):
        """创建定时任务"""
        parser = reqparse.RequestParser()
        parser.add_argument('user_id', type=int, required=True, help='用户ID不能为空')
        parser.add_argument('email', type=str, required=True, help='邮箱不能为空')
        parser.add_argument('frequency', type=str, required=True, choices=('daily', 'weekly', 'monthly'), help='频率必须是daily, weekly或monthly')
        parser.add_argument('day_of_week', type=int)
        parser.add_argument('day_of_month', type=int)
        parser.add_argument('hour', type=int, default=9)
        parser.add_argument('minute', type=int, default=0)
        parser.add_argument('is_active', type=bool, default=True)
        args = parser.parse_args()
        
        # 检查用户是否存在
        user = User.query.get(args['user_id'])
        if not user:
            return api_response({'message': '用户不存在'}, code=404)
        
        # 验证参数
        if args['frequency'] == 'weekly' and (args['day_of_week'] is None or args['day_of_week'] < 0 or args['day_of_week'] > 6):
            return api_response({'message': '周任务必须指定有效的星期几(0-6)'}, code=400)
            
        if args['frequency'] == 'monthly' and (args['day_of_month'] is None or args['day_of_month'] < 1 or args['day_of_month'] > 31):
            return api_response({'message': '月任务必须指定有效的日期(1-31)'}, code=400)
        
        # 创建定时任务
        task = ScheduledTask(
            user_id=args['user_id'],
            email=args['email'],
            frequency=args['frequency'],
            day_of_week=args['day_of_week'] if args['frequency'] == 'weekly' else None,
            day_of_month=args['day_of_month'] if args['frequency'] == 'monthly' else None,
            hour=args['hour'],
            minute=args['minute'],
            is_active=args['is_active']
        )
        
        try:
            db.session.add(task)
            db.session.commit()
            return api_response(task.to_dict(), message='定时任务创建成功')
        except Exception as e:
            logger.error(f"Failed to create scheduled task: {str(e)}")
            return api_response({'message': '创建定时任务失败'}, code=500)

class ScheduledTaskDetail(Resource):
    def get(self, task_id):
        """获取定时任务详情"""
        task = ScheduledTask.query.get(task_id)
        if not task:
            return api_response({'message': '定时任务不存在'}, code=404)
        
        return api_response(task.to_dict())
    
    def put(self, task_id):
        """更新定时任务"""
        task = ScheduledTask.query.get(task_id)
        if not task:
            return api_response({'message': '定时任务不存在'}, code=404)
        
        parser = reqparse.RequestParser()
        parser.add_argument('email', type=str)
        parser.add_argument('frequency', type=str, choices=('daily', 'weekly', 'monthly'))
        parser.add_argument('day_of_week', type=int)
        parser.add_argument('day_of_month', type=int)
        parser.add_argument('hour', type=int)
        parser.add_argument('minute', type=int)
        parser.add_argument('is_active', type=bool)
        args = parser.parse_args()
        
        # 更新字段
        if args['email'] is not None:
            task.email = args['email']
            
        if args['frequency'] is not None:
            task.frequency = args['frequency']
            
        if args['hour'] is not None:
            task.hour = args['hour']
            
        if args['minute'] is not None:
            task.minute = args['minute']
            
        if args['is_active'] is not None:
            task.is_active = args['is_active']
        
        # 根据频率更新相关字段
        if args['frequency'] is not None or args['day_of_week'] is not None:
            if task.frequency == 'weekly' or args['frequency'] == 'weekly':
                if args['day_of_week'] is not None:
                    if args['day_of_week'] < 0 or args['day_of_week'] > 6:
                        return api_response({'message': '星期几必须在0-6之间'}, code=400)
                    task.day_of_week = args['day_of_week']
                elif task.day_of_week is None:
                    return api_response({'message': '周任务必须指定星期几'}, code=400)
            else:
                task.day_of_week = None
                
        if args['frequency'] is not None or args['day_of_month'] is not None:
            if task.frequency == 'monthly' or args['frequency'] == 'monthly':
                if args['day_of_month'] is not None:
                    if args['day_of_month'] < 1 or args['day_of_month'] > 31:
                        return api_response({'message': '日期必须在1-31之间'}, code=400)
                    task.day_of_month = args['day_of_month']
                elif task.day_of_month is None:
                    return api_response({'message': '月任务必须指定日期'}, code=400)
            else:
                task.day_of_month = None
        
        try:
            db.session.commit()
            return api_response(task.to_dict(), message='定时任务更新成功')
        except Exception as e:
            logger.error(f"Failed to update scheduled task: {str(e)}")
            return api_response({'message': '更新定时任务失败'}, code=500)
    
    def delete(self, task_id):
        """删除定时任务"""
        task = ScheduledTask.query.get(task_id)
        if not task:
            return api_response({'message': '定时任务不存在'}, code=404)
        
        try:
            db.session.delete(task)
            db.session.commit()
            return api_response(None, message='定时任务删除成功')
        except Exception as e:
            logger.error(f"Failed to delete scheduled task: {str(e)}")
            return api_response({'message': '删除定时任务失败'}, code=500)